using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.Configuration;

namespace Starznet.SharePoint.SPDAT.ApplicationPages.Settings
{
    public class MembershipDeleteUserPage : LayoutsPageBase
    {
        protected Label lblConfirmDelete;
        protected Literal lblConfirm;
        protected Panel pnlConfirmSuccess;
        protected Panel pnlForm;

        private string _sUsername;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            _sUsername = Request.QueryString["Username"].ToString();
            String sConfirm = this.GetGlobalResourceObject("szadm", "DeleteUser_Confirm").ToString();
            this.lblConfirmDelete.Text = String.Format(sConfirm, _sUsername);
        }

        protected void BtnUpdateUser_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                bool bUserExist = true;
                SPWeb oWeb = SPContext.Current.Web;
                MembershipUser oUser = Membership.GetUser(_sUsername, false);
                String sUserNameProvider = oUser.ProviderName + ":" + oUser.UserName;

                try { SPUser oSPUser = oWeb.AllUsers[sUserNameProvider]; }
                catch { bUserExist = false; }

                if (bUserExist)
                {
                    oWeb.AllowUnsafeUpdates = true;
                    oWeb.SiteUsers.Remove(sUserNameProvider);
                    oWeb.Update();
                    oWeb.AllowUnsafeUpdates = false;
                }

                Membership.DeleteUser(oUser.UserName, true);
            });

            this.pnlForm.Visible = false;
            this.pnlConfirmSuccess.Visible = true;
        }
    }
}
